package com.kuanter.kuanterauto.baseui;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Toast;

import com.kuanter.kuanterauto.R;


/**
 * 没有导航栏的基础Activity
 * 
 * @author soup
 * 
 */
public abstract class BaseActivity_NoBar extends Activity implements
		OnClickListener {

	public ProgressDialog progressDialog = null;
	
	public int screenWidth;
	public int screenHeight;

	protected void showToast(String message) {
		Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
	}

	// 带位置的Toast
	protected void showToast(String message, int left, int top) {
		Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.TOP | Gravity.LEFT, left, top);
		toast.show();
	}

	/**
	 * 显示异步上传时的等待进度框
	 * 
	 * @param message
	 *            进度框内容文字
	 */
	protected void showProgress(String message) {
		if(progressDialog == null) {
			progressDialog = new ProgressDialog(BaseActivity_NoBar.this);
			progressDialog.setCanceledOnTouchOutside(false);
//			progressDialog.setCancelable(false);
			progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			progressDialog.setMessage(message);
			progressDialog.show();
			progressDialog.setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					finish();
				}
			});
		} else if(!progressDialog.isShowing()) {
			progressDialog.setCanceledOnTouchOutside(false);
//			progressDialog.setCancelable(false);
			progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			progressDialog.setMessage(message);
			progressDialog.show();
			progressDialog.setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					finish();
				}
			});
		}
	}
	
//	public ProgressDialog getDialog() {
//		return progressDialog;
//	}

	/**
	 * 结束进度框
	 * 
	 * @param progress
	 */
	protected void finishProgress() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	/** 打开新的Activity */
	protected void qStartActivity(Class<?> cls, Bundle bundle) {
		Intent intent = new Intent();
		if (bundle != null)
			intent.putExtras(bundle);
		intent.setClass(this, cls);
		startActivity(intent);
	}

	/** 打开新的Activity */
	protected void qStartActivity(Class<?> cls, Bundle bundle, String action) {
		Intent intent = new Intent(action);
		if (bundle != null)
			intent.putExtras(bundle);
		intent.setClass(this, cls);
		startActivity(intent);
	}

	/** 打开新的Activity for result */
	protected void qStartActivityForResult(Class<?> cls, Bundle bundle,
			int requestCode) {
		Intent intent = new Intent();
		if (bundle != null)
			intent.putExtras(bundle);
		intent.setClass(this, cls);
		startActivityForResult(intent, requestCode);
	}

	/** 带结果返回上一个activity， 配合qStartActivityForResult使用 */
	protected void qBackForResult(int resultCode, Bundle bundle) {
		Intent intent = new Intent();
		if (bundle != null)
			intent.putExtras(bundle);
		setResult(resultCode, intent);
		finish();
	}

	/** 回到之前的Activity */
	protected void qBackToActivity(Class<?> cls, Bundle bundle) {
		Intent intent = new Intent();
		if (bundle != null)
			intent.putExtras(bundle);
		intent.setClass(this, cls);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_SINGLE_TOP);
		startActivity(intent);
	}

	/** 回到之前的Activity */
	protected void qBackToActivity(Class<?> cls, Bundle bundle, String action) {
		Intent intent = new Intent(action);
		if (bundle != null)
			intent.putExtras(bundle);
		intent.setClass(this, cls);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_SINGLE_TOP);
		startActivity(intent);
	}

	public String getProxyHost(boolean isDefault) {
		if (!isDefault)
			return android.net.Proxy.getHost(this);
		else
			return android.net.Proxy.getDefaultHost();
	}

	public int getProxyPort(boolean isDefault) {
		if (!isDefault)
			return android.net.Proxy.getPort(this);
		else
			return android.net.Proxy.getDefaultPort();
	}

	// public void prepareRun() {
	// NetworkInfo info = getNetworkInfo();
	// if (info != null) {
	// if (info.getType() == ConnectivityManager.TYPE_WIFI) {
	// // WIFI: global http proxy
	// HttpTask.proxyHost = getProxyHost(false);
	// HttpTask.proxyPort = getProxyPort(false);
	// if (HttpTask.proxyHost != null && HttpTask.proxyHost.length() > 0
	// &&
	// HttpTask.proxyHost.equalsIgnoreCase(android.net.Proxy.getDefaultHost()))
	// {
	// HttpTask.proxyHost = null;
	// }
	// } else {
	// // GPRS: APN http proxy
	// HttpTask.proxyHost = getProxyHost(true);
	// HttpTask.proxyPort = getProxyPort(true);
	// }
	// }
	// }

	public NetworkInfo getNetworkInfo() {
		ConnectivityManager connMgr = (ConnectivityManager) this
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		return connMgr.getActiveNetworkInfo();
	}

	public void call(String number) {
		Uri callUri = Uri.parse("tel:" + number);
		Intent call = new Intent(Intent.ACTION_CALL, callUri);
		startActivity(call);
	}

	/** ---activity 动画 **/
	protected void startActivity_anim(int num) {
		switch (num) {
		case 0:// 淡入淡出效果
			overridePendingTransition(R.anim.fade, R.anim.hold);
			break;
		case 1:// 放大淡出效果
			overridePendingTransition(R.anim.my_scale_action,
					R.anim.my_alpha_action);
			break;
		case 2:// 转动淡出效果1
			overridePendingTransition(R.anim.scale_rotate,
					R.anim.my_alpha_action);
			break;
		case 3:// 转动淡出效果2
			overridePendingTransition(R.anim.scale_translate_rotate,
					R.anim.my_alpha_action);
			break;
		case 4:// 左上角展开淡出效果
			overridePendingTransition(R.anim.scale_translate,
					R.anim.my_alpha_action);
			break;
		case 5:// 压缩变小淡出效果
			overridePendingTransition(R.anim.hyperspace_in,
					R.anim.hyperspace_out);
			break;
		case 6:// 右往左推出效果
			overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
			break;
		case 7:// 下往上推出效果
			overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
			break;
		case 8:// 左右交叉效果
			overridePendingTransition(R.anim.slide_left, R.anim.slide_right);
			break;
		case 9:// 放大淡出效果
			overridePendingTransition(R.anim.wave_scale, R.anim.my_alpha_action);
			break;
		case 10:// 缩小效果
			overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
			break;
		case 11:// 上下交错效果
			overridePendingTransition(R.anim.slide_up_in, R.anim.slide_down_out);
			break;
		}
	}

	// 是否是手机号
	public boolean isPhoneNum(String phoneNum) {
		String regExp = "^[1]([3][0-9]{1}|59|58|88|89|86|53|80|85|47|50|51|52|57|59|82|87|55|81|83|84|54|56|45)[0-9]{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(phoneNum);
		return m.find();// boolean
	}

	// 是否包含汉子
	public boolean isHanZi(String str) {
		Pattern p = Pattern.compile("^[\u4e00-\u9fa5]");
		Matcher m = p.matcher(str);
		return m.find();
	}

	// 是否包含英文
	public boolean isE(String str) {
		Pattern p = Pattern.compile("^[A-Za-z]+$");
		Matcher m = p.matcher(str);
		return m.find();
	}

	// 判断网络是否可用
	public boolean CheckNetworkState() {
		boolean flag = false;
		ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (manager.getActiveNetworkInfo() != null) {
			flag = manager.getActiveNetworkInfo().isAvailable();
		}
		if (!flag) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setIcon(android.R.drawable.ic_dialog_alert);
			builder.setTitle("网络状况");
			builder.setMessage("当前网络不可用，是否设置网络");
			builder.setPositiveButton("设置",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
//							Intent mIntent = new Intent("/");
//							ComponentName comp = new ComponentName(
//									"com.android.settings",
//									"com.android.settings.WirelessSettings");
//							mIntent.setComponent(comp);
//							mIntent.setAction("android.intent.action.VIEW");
//							startActivity(mIntent);

							if (android.os.Build.VERSION.SDK_INT > 10) {
								// 3.0以上打开设置界面
								startActivity(new Intent(
										android.provider.Settings.ACTION_SETTINGS));
								
							} else {
								startActivity(new Intent(
										android.provider.Settings.ACTION_WIRELESS_SETTINGS));
							}
						}
					});
			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
							finish();
						}
					});
			builder.create();
			builder.show();
		}

		return flag;

	}

	/*@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return false;
	}*/
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		screenWidth = dm.widthPixels;
		screenHeight = dm.heightPixels;
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void onStop() {
		super.onStop();
//		if(!isAppOnForeground()) {
//			Log.i("bbb", "清除缓存");
//			ProApplication.getInstance().clearCache();
//		}
	}
	
	
	public boolean isAppOnForeground() {
		// Returns a list of application processes that are running on the
		// device

		ActivityManager activityManager = (ActivityManager) getApplicationContext()
				.getSystemService(Context.ACTIVITY_SERVICE);
		String packageName = getApplicationContext().getPackageName();

		List<RunningAppProcessInfo> appProcesses = activityManager
				.getRunningAppProcesses();
		if (appProcesses == null)
			return false;

		for (RunningAppProcessInfo appProcess : appProcesses) {
			// The name of the process that this object is associated with.
			if (appProcess.processName.equals(packageName)
					&& appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
				return true;
			}
		}

		return false;
	}
	
	// 判断当前是否使用的是 WIFI网络  
    public boolean isWifiActive(Context icontext){
        Context context = icontext.getApplicationContext();    
        ConnectivityManager connectivity = (ConnectivityManager) context    
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] info;
        if (connectivity != null) {    
            info = connectivity.getAllNetworkInfo();    
            if (info != null) {    
                for (int i = 0; i < info.length; i++) {    
                    if (info[i].getTypeName().equals("WIFI") && info[i].isConnected()) {    
                        return true;    
                    }    
                }    
            }    
        }    
        return false;   
    }
	
}
